/*
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package botobjects;

import interfaces.BotObject;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.jibble.pircbot.Colors;

import tools.StringTools;
import tools.UtopiaTime;
import database.DBConnectionFactory;

/**
 * Represents a Quote
 * 
 * 
 */
public class Quote implements BotObject {
   /**
    * Removes the specified quote
    * 
    * @param args
    *           specifies the id of the quote to remove
    * @return true if the quote is successfully deleted
    */
   public static boolean deleteFromDB(final String... args) {
	  boolean out = false;
	  if (args.length < 1)
		 return out;
	  int id = 0;
	  try {
		 id = Integer.parseInt(args[0]);
	  } catch (NumberFormatException e) {
		 Logger.getLogger("Error").error("", e);
		 return out;
	  }
	  PreparedStatement ps = null;
	  try {
		 ps = DBConnectionFactory.getConnectionHandler().getConnection().prepareStatement("DELETE FROM quote WHERE id = ?");
		 ps.setInt(1, id);

		 if (ps.executeUpdate() == 1) {
			out = true;
		 }
	  } catch (final SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			ps.close();
		 } catch (final Exception e) {
		 }
	  }
	  return out;
   }

   /**
    * Returns the specified quote, or a random quote if id is -1
    * 
    * @param id
    * @return a Quote object. Returns null if no quote is found
    */
   public static Quote getQuote(final int id) {
	  Quote out = null;
	  PreparedStatement ps = null;
	  ResultSet rs = null;
	  try {
		 if (id == -1) {
			ps = DBConnectionFactory.getConnectionHandler().getConnection()
				  .prepareStatement("SELECT * FROM quote ORDER BY rand() LIMIT 1");
			rs = ps.executeQuery();
			if (rs.next()) {
			   out = new Quote(rs.getInt("id"), rs.getString("message"), rs.getString("addedby"), rs.getTimestamp("addedtime")
					 .getTime());
			}
		 } else {
			ps = DBConnectionFactory.getConnectionHandler().getConnection().prepareStatement("SELECT * FROM quote WHERE id = ?");
			ps.setInt(1, id);
			rs = ps.executeQuery();
			if (rs.next()) {
			   out = new Quote(rs.getInt("id"), rs.getString("message"), rs.getString("addedby"), rs.getTimestamp("addedtime")
					 .getTime());
			}
		 }
	  } catch (final SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			rs.close();
		 } catch (final Exception e) {
		 }
		 try {
			ps.close();
		 } catch (final Exception e) {
		 }
	  }
	  return out;
   }

   /**
    * Returns all quotes
    * 
    * @return a List of Quote objects
    */
   public static List<Quote> getQuotes() {
	  List<Quote> out = new LinkedList<Quote>();
	  PreparedStatement ps = null;
	  ResultSet rs = null;
	  try {
		 ps = DBConnectionFactory.getConnectionHandler().getConnection().prepareStatement("SELECT * FROM quote");
		 rs = ps.executeQuery();
		 while (rs.next()) {
			out.add(new Quote(rs.getInt("id"), rs.getString("message"), rs.getString("addedby"), rs.getTimestamp("addedtime")
				  .getTime()));
		 }
	  } catch (final SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			rs.close();
		 } catch (final Exception e) {
		 }
		 try {
			ps.close();
		 } catch (final Exception e) {
		 }
	  }
	  return out;
   }

   private int id = 0;

   private String quote = "";

   private String poster = "";

   private Long posted = 0L;

   public Quote(final int id, final String quote, final String poster, final Long posted) {
	  this.id = id;
	  this.quote = quote;
	  this.poster = poster;
	  this.posted = posted;
   }

   public int getId() {
	  return id;
   }

   @Override
   public List<String> getIRCOutput(final int outputType, final String... args) {
	  List<String> out = new LinkedList<String>();
	  if (StringTools.isNullOrEmpty(getQuote()) || StringTools.isNullOrEmpty(getPoster()) || getPosted() == null)
		 return out;
	  out.add(Colors.OLIVE + "Quote: " + Colors.BLUE + getId() + Colors.OLIVE + " added by " + Colors.BLUE + getPoster() + " "
			+ UtopiaTime.compareTimes(getPosted()) + Colors.NORMAL + " ago:");
	  out.add(getQuote());
	  return out;
   }

   public Long getPosted() {
	  return posted;
   }

   public String getPoster() {
	  return poster;
   }

   public String getQuote() {
	  return quote;
   }

   @Override
   public Map<String, Object> getRPCOutput(final int... includes) {
	  Map<String, Object> out = new HashMap<String, Object>();
	  if (StringTools.isNullOrEmpty(getQuote()) || StringTools.isNullOrEmpty(getPoster()) || getPosted() == null)
		 return out;
	  out.put("ID", getId());
	  out.put("Quote", getQuote());
	  out.put("Poster", getPoster());
	  out.put("Posted Time", new Date(getPosted()));
	  return out;
   }

   @Override
   public boolean saveToDB() {
	  boolean out = false;
	  if (StringTools.isNullOrEmpty(getQuote()) || StringTools.isNullOrEmpty(getPoster()) || getPosted() == null)
		 return out;
	  PreparedStatement ps = null;
	  ResultSet rs = null;
	  try {
		 ps = DBConnectionFactory.getConnectionHandler().getConnection()
			   .prepareStatement("INSERT INTO quote VALUES(default,?,?,?)");
		 ps.setString(1, getQuote());
		 ps.setString(2, getPoster());
		 ps.setTimestamp(3, new Timestamp(getPosted()));
		 int i = ps.executeUpdate();

		 try {
			ps.close();
		 } catch (final Exception e) {
		 }

		 ps = DBConnectionFactory.getConnectionHandler().getConnection()
			   .prepareStatement("SELECT id FROM " + "quote WHERE message = ? ORDER BY addedtime DESC");
		 ps.setString(1, getQuote());
		 rs = ps.executeQuery();

		 if (i == 1 && rs.next()) {
			out = true;
			id = rs.getInt("id");
		 }
	  } catch (final SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			rs.close();
		 } catch (final Exception e) {
		 }
		 try {
			ps.close();
		 } catch (final Exception e) {
		 }
	  }
	  return out;
   }

}
